<?php

namespace App\Kuafu\Common\Controller\B;

use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\UploadImageException;
use App\Kuafu\Common\Service\CommonService;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Common\Validate\CommonValidate;

class UploadController extends BaseController
{

    public function ImagesUpload(Request $request, int $type = 0)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');

            $allowed_extensions = ['png', 'jpg', 'jpeg', 'gif'];
            if (!in_array(strtolower($file->getClientOriginalExtension()), $allowed_extensions)) {
                throw new UploadImageException(CommonCodeEnum::ERR_UPLOAD_IMAGE_EXT_ERROR, '只能上传png,jpg和gif格式的图片.');
            }

            $size = 1000; // 200K 大小的
            if ($file->getSize() > $size * 1024) {
                throw new UploadImageException(CommonCodeEnum::ERR_UPLOAD_IMAGE_SIZE_ERROR,
                    '只能上传 ' . $size . 'Kb 以内的图片.');
            }

            $destinationPath = public_path() . '/storage/uploads/images/';
            $extension       = strtolower($file->getClientOriginalExtension());

            $filePath = $request->header('brandId') . '/' . $request->header('shopId') . '/';

            // 0 目录已经撑爆了, 换个目录
            if ($request->header('shopId') == 0) {
                $filePath = $request->header('brandId') . '/00/';
            }
            $fileName = md5($file->getContent()) . '.' . $extension;
            // 设置前缀
            $prefix1 = substr($fileName, 0, 2);
            $prefix2 = substr($fileName, 2, 2);
            $filePath .= $prefix1 . '/' . $prefix2 . '/';
            $file->move($destinationPath . $filePath, $fileName);
            $filePath = CommonService::joinImageUrl($filePath . $fileName);

            if ($type) {// 商家端 返回url 兼容之前的
                $data = ['url' => $filePath];
            } else {
                $data = ['fileUrl' => $filePath];
            }
            return $this->success($data);
        } else {
            throw new UploadImageException(CommonCodeEnum::ERR_UPLOAD_IMAGE_EXT_ERROR, '只能上传png,jpg和gif格式的图片.');
        }
    }


    public function ImagesUploads(Request $request)
    {
        return self::ImagesUpload($request, 1);
    }
}
